from elasticsearch import Elasticsearch
import json_pac
from xpinyin import Pinyin

class Elasticdemo:
 def __init__(self,index_name,index_type,ip,port):
  self.index_name = index_name
  self.index_type = index_type
  self.ip = ip
  self.port = port
  self.conn = Elasticsearch([{'host':ip,'port':port}])
  if self.conn.ping():
   print('Connecting.')
  else:
   print('Something Error.')

 def info(self):
  print (self.conn.info())

 def close(self):
  if self.conn is not None:
   try:
    self.conn.close()
   except Exception as e:
    print (e.reason)
   finally:
    self.conn = None
    
 """
 查询是否已存在列
 """   
 def exists_column(self,column_name):
     query = {'query': {'term': {'column_name': column_name}}}
     #print("查询column_name是否存在")
     #print(column_name)
     res =  self.conn.search(index=self.index_name,doc_type=self.index_type,body=query)
     total=res['hits']['total']
     if (total>0):
         id=res['hits']['hits'][0]['_id']
     else:
         id=None
     data = {"total":total,"id":id} 
     return  data
     

 """
  定义添加列的函数
  column 为空时
 """
 def add_column(self, column_json):
   if None != column_json:
     #get existed columns 
     #if not exists ,add column 
     #print(column_json['column_name'])
     #exists_column(column_json['column_name'])
     self.conn.index(index=self.index_name,doc_type=self.index_type,body=column_json)
     print('添加列%s成功' % column_json['column_name'])
     return 200,'添加--成功'
   else:
     print('添加列%s失败'%column)
     return 400,'添加失败'
 def del_column(self, column):
   if None != column and len(column)>0:
     #get existed columns , if not exists ,add column 
     print('删除列%s成功',column)
   else:
     print('删除列%s失败',column)  
 """
 定义添加一行数据的函数
 """
 def add_or_update_row(self, row):
   #查找es中name是否已存在，存在则更新，否则插入es
   print('添加行成功')
   
 """
 定义删除一行数据的函数
 """
 def del_row(self, row):
   #查找es中name是否存在，存在则删除
   print('删除行成功')
   
 """
 定义查询数据的函数
 """
 def query_all(self, name):
    #查找es中name是否已存在，存在则返回json
   print('添加行成功')  
    
 def insert_single(self,data,id_num=1):
   res = self.conn.index(index=self.index_name,doc_type=self.index_type,body=data,id=id_num)
   return json_pac.packet_message(['operate','status'],['insert',res['result']])

 def insert_by_id(self,list,startnum):
  for data in list:
   result = self.insert_single(data,id_num=startnum)
   #print str(result)+" id:"+str(startnum)+". data:"+str(data)
   print (json_pac.packet_message(['message'],[result]))
   startnum += 1

 def get_single(self,id_num):
  try:
   res = self.conn.get(index=self.index_name,doc_type=self.index_type,id=id_num)
   return json_pac.packet_message(['operate','data'],['search',res['_source']])
  except:
   return json_pac.packet_message(['operate','message'],['search',"Search Failed.Error:id"+"="+str(id_num)+" may out of index or other situation."])

 def get_by_id(self,num1,num2):
  for i in range(num1,num2+1):
   result = self.get_single(i)
   print (json_pac.packet_message(['id','message'],[str(i),str(result)]))

 def search_by_query(self,query):
  try:
   res = self.conn.search(index=self.index_name,doc_type=self.index_type,body=query)
  except:
   print (json_pac.packet_message(['message'],["Search Failed.Error:query"+"="+str(query)+" may has something wrong."]))
  else:
   for element in res['hits']['hits']:
    print (json_pac.packet_message(['data'],[element['_source']]))

 def delete_single(self,id_num):
  try:
   res = self.conn.delete(index=self.index_name,doc_type=self.index_type,id=id_num)
  except:
   #return "Delete Failed.Error:id"+"="+str(id_num)+" may has no data or other situation."
   return 404,'删除失败'

  else:
   if res['_shards']['successful']==1:
    result = 'Delete Successfully.'
    #return "index_name:"+self.index_name+" doc_type:"+self.index_type+" id:"+str(id_num)+" "+result
    return 200,'删除成功'
   else:
    result = 'Delete Failed.'
    #return "index_name:"+self.index_name+" doc_type:"+self.index_type+" id:"+str(id_num)+" "+result
    return 404,'删除失败'
 

 def delete_by_id_batch(self,num1,num2):
  for i in range(num1,num2+1):
   result = self.delete_single(i)
   print (result)

 def delete_query(self,query):
  try:
   res =  self.conn.delete_by_query(index=self.index_name,doc_type=self.index_type,body=query)
  except:
   return "Delete Failed.Error:query"+"="+str(query)+" may has no data or other situation."
  else:
   if res['deleted'] == 1:
    return "Delete Successfully."
   else:
    return "Delete Failed."

 #def update_single(self,id_num,data):
  #self.conn.update(index=self.index_name,doc_type=self.index_type,id=id_num,body=data)

 #def update_by_id_batch(self,startnum,list):
  #for data in list:
   #update_single(startnum,data)
   #start += 1

 #def update_query(self,query):
  #self.conn.update_by_query(index=self.index_name,doc_type=self.index_type,body=query)

#o = Elasticdemo('info_manager','columns','localhost','9200')
#data=o.get_single("0eGVS2gBeU-m1JYwdJw8")
#print(data)
#pin = Pinyin()
#print("请输入属性的名字和值，name,value"+"\n")
#column_desc,value=input().split(",")
#column_name=pin.get_pinyin(column_desc,"")
#true=o.exists_column(column_name)
#if(true>0):
#    print("该列已存在,请重新输入属性的名字和值，格式如：身高,175")
#column_json={
# "column_name": column_name,
# "column_desc": column_desc,
# "default_value": value,
# "type": "int",
# "length": 100
#}
#res=o.add_column(column_json)



#print(res)
#o.insert_by_id([{'a':'5','b':'6'},{'a':'0','b':'9'}],1)
#print o.insert_single({'m':'1','n':2},1)
#o.update_by_id_batch(1,2,[{'m':'1','n':2},{'m':'3','n':'4'}])
#o.delete_by_id_batch(1,3)
#o.update_single(1,{'m':'2','n':2})
#o.get_by_id(1,3)
#o.delete_by_id_batch(1,3)
#print o.get_single(1)
#print o.delete_single(1)
